using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Hematology.Data
{
	[DataObject]
	[Serializable]
	public partial class Country
	{

		#region Constants

		private const string TableName = "[dbo].[Country]";

		#endregion

		#region Properties

		public int? Id { get; set; }
		public string Name { get; set; }
		public bool? IsVisible { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("Id", typeof(Int32));
			ds.Tables[TableName].Columns.Add("Name", typeof(String));
			ds.Tables[TableName].Columns.Add("IsVisible", typeof(Boolean));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["Id"] = Id ?? (object) DBNull.Value;
			dr["Name"] = Name ?? (object) DBNull.Value;
			dr["IsVisible"] = IsVisible ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			Id = dr["Id"] != DBNull.Value ? Convert.ToInt32(dr["Id"]) : Id = null;
			Name = dr["Name"] != DBNull.Value ? Convert.ToString(dr["Name"]) : Name = null;
			IsVisible = dr["IsVisible"] != DBNull.Value ? Convert.ToBoolean(dr["IsVisible"]) : IsVisible = null;
		}

		public static List<Country> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<Country> objects = new List<Country>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");
			
			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[Country] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[Country] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				Country instance = new Country();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		public static Country Get(Int32 id)
		{
			Country instance = new Country();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, id))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0) throw new ApplicationException(String.Format("Could not get Country ID:{0} from Database.", id));
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(Int32? id, String name, Boolean? isVisible, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, id, name, isVisible))
			{
				if (transaction == null)
					db.ExecuteScalar(dbCommand);
				else
					db.ExecuteScalar(dbCommand, transaction);
			}
		}

		/// <summary>
		/// Insert current Country to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(Id, Name, IsVisible, transaction);
		}

		#endregion


		#region UPDATE

		public static void Update(Int32? id, String name, Boolean? isVisible, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@id"].Value = id;
				dbCommand.Parameters["@name"].Value = name;
				dbCommand.Parameters["@isVisible"].Value = isVisible;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		public static void Update(Int32? id, String name, Boolean? isVisible)
		{
			Update(id, name, isVisible, null);
		}

		public static void Update(Country country)
		{
			country.Update();
		}

		public static void Update(Country country, DbTransaction transaction)
		{
			country.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		public void Update(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@id"].SourceColumn = "Id";
				dbCommand.Parameters["@name"].SourceColumn = "Name";
				dbCommand.Parameters["@isVisible"].SourceColumn = "IsVisible";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();

					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		public void Update()
		{
			Update((DbTransaction)null);
		}
		#endregion


		#region DELETE
		public static void Delete(Int32? id, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, id))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		public static void Delete(Int32? id)
		{
			Delete(
				id);
		}

		/// <summary>
		/// Delete current Country from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		public void Delete(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, Id))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		/// <summary>
		/// Delete current Country from database.
		/// </summary>
		public void Delete()
		{
			Delete((DbTransaction)null);
		}

		#endregion

		#region SEARCH
		
		private static List<Country> Search(Int32? id, String name, Boolean? isVisible)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspCountry_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, id, name, isVisible))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}

		private static List<Country> Search(Country searchObject)
		{
			return Search(searchObject.Id, searchObject.Name, searchObject.IsVisible);
		}

		#endregion

		#endregion

		#endregion
	}
}

